package com.example.onlinemarket.interceptor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class LoginInterceptor implements HandlerInterceptor {
    @Override//目标方法运行前运行
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String path = request.getServletPath();
        //只拦截如下页面
        if(!(path.contains("search")||path.contains("add")||path.contains("del")
                ||path.contains("get")||path.contains("update")||path.contains("shopping")
                ||path.contains("shop")))
            return true;
        HttpSession session = request.getSession();
        Object flag =  session.getAttribute("isLogin");
        if ((flag==null)||(!(boolean)flag)) {
            request.setAttribute("loginMsg", "请先登录！");
            Logger logger = LoggerFactory.getLogger(LoginInterceptor.class);
            logger.debug("\n--用户未登录--\n");
            request.getRequestDispatcher("/login").forward(request, response);
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        //System.out.println("拦截器1：---preHandle方法运行---");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //System.out.println("拦截器1：---preHandle方法运行---");
    }
}
